# _*_ coding: utf-8 _*_
# @Author : lxx
# @time   : 2021/7/27 15:30
# @File   : music163_search.py
# Software: PyCharm

import requests
import execjs
import json


def js_design(song_keyword):
    """

    :param song_keyword: 搜索关键词
    :return: js解析后获取的参数
    """
    js_code = str(open(r'core1.js', 'r', encoding='utf-8').read())

    p2 = '010001'
    p3 = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
    p4 = '0CoJUm6Qyw8W8jud'

    params = execjs.compile(js_code).call('d', '{"hlpretag":"","hlposttag":"","s":"'+song_keyword+'","type":"1","offset":"0","total":"true","limit":"30","csrf_token":""}',p2,p3,p4)
    return params


def get_song_list(params):
    """
    POST请求获取歌曲列表 https://music.163.com/#/search/m/?id=2592268&s=薛之谦&type=1
    :param params:
    :return:
    """
    data = {
        'params': params['encText'],
        'encSecKey': params['encSecKey'],
    }
    url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
    response = requests.post(url, data=data)
    content = json.loads(response.text)
    song_list = content['result']['songs']
    return song_list


def download_song(song):
    """
    下载所需要的信息
    :param song: 歌曲信息
    :return:
    """
    item = {
        'title': song['name'] + '_' + song['ar'][0]['name'],    # 格式：歌曲名_作者名（变废为宝_薛之谦）
        'song_id': song['id'],
        'author': song['ar'][0]['name'],
        'video_url': 'https://music.163.com/song?id={}'.format(song['id']),
        'download_url': 'http://music.163.com/song/media/outer/url?id={}.MP3'.format(song['id'])
    }
    # TODO：下载download_url部分没写
    return item


def search(keyword):
    params = js_design(keyword)
    song_list = get_song_list(params)
    result_list=[]
    for song in song_list:
        item = download_song(song)
        result_list.append(item)
    return result_list


if __name__ == '__main__':
    keyword = '薛之谦'
    search(keyword)
